using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using xjjxmm.infrastructure.Authorizations;
using XjjXmm.Infrastructure.Configuration;
using XjjXmm.Infrastructure.Constant;
using XjjXmm.Infrastructure.Exceptions;
using xjjxmm.infrastructure.ToolKit;
using XjjXmm.Infrastructure.User;
using System.Reflection;
using System;
using XjjXmm.Infrastructure.Common;
using XjjXmm.Infrastructure.ToolKit;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using xjjxmm.infrastructure.Webs;
using xjjxmm.infrastructure.xjjxmmLog.LogKit;
using System.Text;
using System.Diagnostics;
using System.Globalization;

namespace xjjxmm.infrastructure.Middleware;

public class CultureMiddleware : IMiddleware
{
    private readonly ThreadLocalContext _threadLocalContext;

    public CultureMiddleware(ThreadLocalContext threadLocalContext)
    {
        _threadLocalContext = threadLocalContext;
    }
    
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        var lang = context.Request.Headers["Accept-Language"].ToString().ToLower();
        var langs = lang.Split(";").FirstOrDefault()?.Split(",").ToList()??new List<string>();

        var culture = CultureInfo.CurrentCulture.Name.ToLower();
        langs.Add(culture);
        
        _threadLocalContext.Set(CacheKey.CULTURE, langs);
        
        await next.Invoke(context);
    }
}